package com.liangsui.mss.srevice.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.liangsui.mss.constants.Constants;
import com.liangsui.mss.domain.*;
import com.liangsui.mss.dto.CareHistoryDto;
import com.liangsui.mss.dto.CareOrderDto;
import com.liangsui.mss.dto.CareOrderFormDto;
import com.liangsui.mss.dto.CareOrderItemDto;
import com.liangsui.mss.mapper.*;
import com.liangsui.mss.service.CareService;
import com.liangsui.mss.service.MedicinesService;
import com.liangsui.mss.utils.IdGeneratorSnowflake;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;

import java.math.BigDecimal;
import java.util.List;

/**
 * CareServiceImpl
 *
 * @author zhangjiawei
 * @email 1533167396@qq.com
 * @date 2022/12/7 17:11
 */
@DubboService(timeout = 5000)
public class CareServiceImpl implements CareService {

    @Autowired
    private OrderChargeItemMapper orderChargeItemMapper;

    @DubboReference
    private MedicinesService medicinesService;

    @Autowired
    private CareHistoryMapper careHistoryMapper;

    @Autowired
    private CareOrderMapper careOrderMapper;

    @Autowired
    private CareOrderItemMapper careOrderItemMapper;

    @Autowired
    private RegistrationMapper registrationMapper;

    @Autowired
    private OrderChargeMapper orderCharge;

    /**
     * @功能描述:根据患者ID查询---病例信息
     */
    @Override
    public List<CareHistory> queryCareHistoryByPatientId(String patientId) {
        QueryWrapper<CareHistory> wrapper = new QueryWrapper<>();
        wrapper.eq(CareHistory.COL_PATIENT_ID, patientId);
        List<CareHistory> careHistories = this.careHistoryMapper.selectList(wrapper);
        return careHistories;
    }

    /**
     * @param chId 病例ID
     * @功能描述:根据病例ID查询---处方信息
     */
    @Override
    public List<CareOrder> queryCareOrdersByChId(String chId) {
        QueryWrapper<CareOrder> wrapper = new QueryWrapper<>();
        wrapper.eq(CareOrder.COL_CH_ID, chId);
        return this.careOrderMapper.selectList(wrapper);
    }

    /**
     * @param coId
     * @功能描述:根据处方ID---查询处方详细信息
     */
    @Override
    public List<CareOrderItem> queryCareOrdersItemsByCoId(String coId, String status) {
        QueryWrapper<CareOrderItem> wrapper = new QueryWrapper<>();
        wrapper.eq(CareOrderItem.COL_CO_ID, coId);
        wrapper.eq(StringUtils.isNotBlank(status), CareOrderItem.COL_STATUS, status);//添加的
        return this.careOrderItemMapper.selectList(wrapper);
    }

    /**
     * @Description: 保存病例信息
     * @Param: CareHistory
     * @Return: careHistoryDto
     */
    @Override
    public CareHistory saveOrUpdateCareHistory(CareHistoryDto careHistoryDto) {
        CareHistory careHistory = new CareHistory();
        BeanUtil.copyProperties(careHistoryDto, careHistory);
        if (StringUtils.isNotBlank(careHistory.getChId())) {//修改
            this.careHistoryMapper.updateById(careHistory);
        } else {//添加
            careHistory.setChId(IdGeneratorSnowflake.generatorIdWithProfix(Constants.ID_PREFIX_CH));
            this.careHistoryMapper.insert(careHistory);
        }
        return careHistory;
    }

    /**
     * @param regId
     * @功能描述: 根据挂号ID查询病例信息
     */
    @Override
    public CareHistory queryCareHistoryByRegId(String regId) {
        QueryWrapper<CareHistory> wrapper = new QueryWrapper<>();
        wrapper.eq(CareHistory.COL_REG_ID, regId);
        return this.careHistoryMapper.selectOne(wrapper);
    }

    @Override
    public CareHistory queryCareHistoryByChId(String chId) {
        return this.careHistoryMapper.selectById(chId);
    }

    @Override
    public int visitComplete(String regId) {
        Registration registration = new Registration();
        registration.setRegId(regId);
        registration.setRegStatus(Constants.REG_STATUS_3);
        return this.registrationMapper.updateById(registration);
    }

    /**
     * 保存处方及其明细
     * @param careOrderFormDto
     * @return
     */
    @Override
    public int saveCareOrderItem(CareOrderFormDto careOrderFormDto) {
        CareOrderDto careOrderDto = careOrderFormDto.getCareOrder();
        CareOrder careOrder = new CareOrder();
        BeanUtil.copyProperties(careOrderDto, careOrder);
        careOrder.setCreateBy(careOrderDto.getSimpleUser().getUserName());
        careOrder.setCreateTime(DateUtil.date());
        int i = this.careOrderMapper.insert(careOrder);// 保存处方主表
        List<CareOrderItemDto> careOrderItems = careOrderFormDto.getCareOrderItems();
        careOrderItems.stream().forEach(careOrderItemDto -> {
            CareOrderItem careOrderItem = new CareOrderItem();
            BeanUtil.copyProperties(careOrderItemDto, careOrderItem);
            careOrderItem.setCoId(careOrder.getCoId());
            careOrderItem.setCreateTime(DateUtil.date());
            careOrderItem.setStatus(Constants.ORDER_STATUS_0);// 未支付
            careOrderItem.setItemId(IdGeneratorSnowflake.generatorIdWithProfix(Constants.ID_PREFIX_ITEM));
            this.careOrderItemMapper.insert(careOrderItem);//保存详情数据
        });
        return i;
    }

    /**
     * 删除就诊病例上的处方信息
     * @param itemId
     * @return
     */
    @Override
    public int deleteCareOrderItemById(String itemId) {
        //注意,如果删除了,要更新CareOrder主表上的all_amount
        CareOrderItem careOrderItem = this.careOrderItemMapper.selectById(itemId);
        String coId = careOrderItem.getCoId();//取出主表ID
        //删除
        int i = this.careOrderItemMapper.deleteById(itemId);
        //再根据coId查询还存在的详情数据
        QueryWrapper<CareOrderItem> wrapper = new QueryWrapper<>();
        wrapper.eq(CareOrderItem.COL_CO_ID, coId);
        List<CareOrderItem> careOrderItems = this.careOrderItemMapper.selectList(wrapper);
        if (careOrderItems != null && careOrderItems.size() > 0) {
            //重新计算总价
            BigDecimal allAmount = new BigDecimal("0");
            for (CareOrderItem orderItem : careOrderItems) {
                allAmount = allAmount.add(orderItem.getAmount());
            }
            //根据coId查询主表的数据
            CareOrder careOrder = this.careOrderMapper.selectById(coId);
            careOrder.setAllAmount(allAmount);
            //更新主表数据
            this.careOrderMapper.updateById(careOrder);
        } else {
            //说明没有详情直接删除主表的数据
            this.careOrderMapper.deleteById(coId);
        }
        return i;
    }

    @Override
    public CareOrderItem queryCareOrderItemByItemId(String itemId) {
        return this.careOrderItemMapper.selectById(itemId);
    }

    @Override
    public List<CareOrderItem> queryCareOrderItemsByStatus(String coType, String status) {
        QueryWrapper<CareOrderItem> qw=new QueryWrapper<>();
        qw.eq(StringUtils.isNotBlank(coType),CareOrderItem.COL_ITEM_TYPE,coType);
        qw.eq(StringUtils.isNotBlank(status),CareOrderItem.COL_STATUS,status);
        return this.careOrderItemMapper.selectList(qw);
    }

    @Override
    public CareOrder queryCareOrderByCoId(String coId) {
        return this.careOrderMapper.selectById(coId);
    }

    @Override
    public OrderChargeItem queryOrderChargeItemByItemId(String itemId) {
        return this.orderChargeItemMapper.selectById(itemId);
    }

    @Override
    public List<CareOrderItem> queryCareOrderItemsByCoId(String coId,String status) {
        QueryWrapper<CareOrderItem> qw=new QueryWrapper<>();
        qw.eq(CareOrderItem.COL_CO_ID,coId);
        qw.eq(StringUtils.isNotBlank(status),CareOrderItem.COL_STATUS,status);//添加的
        return this.careOrderItemMapper.selectList(qw);
    }

    @Override
    public OrderCharge queryOrderChargeByOrderId(String coId) {
        return this.orderCharge.selectById(coId);
    }

    @Override
    public String doMedicine(List<String> itemIds) {
        //根据详情ID查询处方详情
        QueryWrapper<CareOrderItem> qw = new QueryWrapper<>();
        qw.in(CareOrderItem.COL_ITEM_ID,itemIds);
        List<CareOrderItem> careOrderItems = this.careOrderItemMapper.selectList(qw);
        StringBuffer sb = new StringBuffer();
        for (CareOrderItem careOrderItem : careOrderItems) {
            //库存扣减
            int i = this.medicinesService.deductionMedicinesStorage(Long.valueOf(careOrderItem.getItemRefId()), careOrderItem.getNum().longValue());
            if(i > 0) {//说明库存够
                //更新处方详情状态
                careOrderItem.setStatus(Constants.ORDER_DETAILS_STATUS_3);//已完成
                this.careOrderItemMapper.updateById(careOrderItem);
                //更新收费详情状态
                OrderChargeItem orderChargeItem=new OrderChargeItem();
                orderChargeItem.setItemId(careOrderItem.getItemId());
                orderChargeItem.setStatus(Constants.ORDER_DETAILS_STATUS_3);
                this.orderChargeItemMapper.updateById(orderChargeItem);
            } else {
                sb.append("【"+careOrderItem.getItemName()+"】发药失败\n");
            }
        }
        if(StringUtils.isBlank(sb.toString())) {
            return null;
        } else {
            sb.append("原因：库存不足");
            return sb.toString();
        }
    }
}
